<?php
class ccdsModuleManager
{
    private $aClasses=array();

    private $ccdSQL;
    private $tools;
    private $BackendUserPlugins=array();

    function __construct( )
    {
        $this->ccdSQL=ccdSQL::getInstance();
        $this->config=ccdsConfig::getInstance();
    }

    function &getInstance( )
    {
        static $obj;

        if ( !$obj )
        {
            $obj=new ccdsModuleManager();
        }
        return $obj;
    }

    function getBackendUserPlugin( $class_id )
    {
        if ( isset( $this->BackendUserPlugins[$class_id] ) )
            return $this->BackendUserPlugins[$class_id];

        $query=
            "SELECT * FROM classes LEFT JOIN extensions ON (class_key_ext_id = ext_id) LEFT JOIN projects ON (ext_key_project_id=project_id) WHERE class_id="
            . $this->ccdSQL->real_escape_string( $class_id );
        $res=$this->ccdSQL->query( $query );
        $row=$this->ccdSQL->fetch_assoc( $res );

        $file=
            $this->config->get( 'EXTENSION_DIR' ) . $row['project_dir'] . "/" . $row['ext_dir'] . "/"
            . $row['class_dir'] . "/backend/" . $row['class_name'] . ".inc.php";

        if ( is_file( $file ) )
        {
            $this->BackendUserPlugins[$class_id]=array
                (
                "file" => $file,
                "class_name" => $row['class_name']
                );

            return $this->BackendUserPlugins[$class_id];
        }
        $this->BackendUserPlugins[$class_id]=false;
        return false;
    }

    function get( $sClass )
    {
        if ( in_array( $sClass, $this->aClasses ) )
            return $aClasses[$sClass];
        $config=ccdsConfig::getInstance();

        if ( is_file( $config->get( 'MODULE_DIR' ) . $sClass . "/" . $sClass . ".inc.php" ) )
        {
            require_once( $config->get( 'MODULE_DIR' ) . $sClass . "/" . $sClass . ".inc.php" );
            $aClasses[$sClass]=new $sClass;
        }
        elseif ( is_numeric( $_REQUEST['ccdsclass_id'] ) )
        {

            $query=
                "SELECT * FROM classes LEFT JOIN extensions ON (class_key_ext_id = ext_id) LEFT JOIN projects ON (ext_key_project_id=project_id) WHERE class_id="
                . $this->ccdSQL->real_escape_string( $_REQUEST['ccdsclass_id'] );
            $res=$this->ccdSQL->query( $query );
            $row=$this->ccdSQL->fetch_assoc( $res );
            $ext_path=
                $this->config->get( 'EXTENSION_DIR' ) . $row['project_dir'] . "/" . $row['ext_dir'] . "/"
                . $row['class_dir'] . "/backend/";
            $file=$ext_path . $row['class_name'] . ".inc.php";

            if ( is_file( $file ) )
            {
                require_once( $file );
                $aClasses[$sClass]=new $sClass( $_REQUEST['ccdsclass_id'], $ext_path );
            }
        }
        else
        {
            return false;
        }
        return $aClasses[$sClass];
    }
}
